package com.abel.bigwater.data.jnrq

import io.netty.buffer.ByteBuf
import kotlin.experimental.and

class UploadEmptyData(_packet: JnrqPacket) : JnrqData() {

    var packet: JnrqPacket? = _packet

    /** 回复序号 */
    var replyCnt: Short? = null

    init {
        dataLen = 12
    }

    /**
     * 计算数据长度，针对解析和打包
     */
    override fun computeDataLen(): Int {
        return dataLen!!
    }

    /**
     * 从当前位置写入打包字节流
     */
    override fun fillBuffer(buf: ByteBuf) {
        val tmp = buf.alloc().buffer()

        tmp.writeBytes(byteArrayOf(0, 0, 0))

        tmp.writeByte(rssi!!.toInt())

        tmp.writeBytes(byteArrayOf(0, 0))

        tmp.writeByte(sendPacketCount!!.toInt()).writeByte(recvPacketCount!!.toInt())

        tmp.writeBytes(byteArrayOf(0, 0))

        tmp.writeByte(swVersion!!.toInt())

        tmp.writeByte(replyCnt!!.toInt())

        // write valid bytes
        buf.writeBytes(tmp)
    }

    /**
     * 解析字节流，从buf当前位置开始，并且消费其中的字节。
     */
    override fun parseBuffer(buf: ByteBuf) {
        val tmp = buf.duplicate()
        fun readByteAsShort() = tmp.readByte().toShort() and 0xFF

        tmp.skipBytes(3)
        rssi = readByteAsShort()
        tmp.skipBytes(2)

        sendPacketCount = readByteAsShort()
        recvPacketCount = readByteAsShort()

        tmp.skipBytes(2)

        swVersion = readByteAsShort()

        replyCnt = readByteAsShort()

        // 消费字节流
        buf.skipBytes(dataLen!!)
    }
}